package ship;

import board.Coordinate;
import board.Direction;

/**
 * @author tymoshya
 * @since 8/4/11
 */
public abstract class Ship implements IShip {
    protected Coordinate firstCoordinate;
    protected Direction direction;
    protected int decks;

    protected int decksAlive;
    protected Coordinate[] coordinates;

    protected Ship(Coordinate firstCoordinate, Direction direction, int decks) {
        this.firstCoordinate = firstCoordinate;
        this.direction = direction;
        this.decks = decks;

        decksAlive = decks;
        locateCoordinates();
    }

    public void looseDeck() {
        --decksAlive;
    }

    public int getDecksAliveCount() {
        return decksAlive;
    }

    public int getDefaultDecksCount() {
        return decks;
    }

    public boolean isAlive() {
        return getDecksAliveCount() > 0;
    }

    public Direction getDirection() {
        return direction;
    }

    public Coordinate getFirstCoordinate() {
        return firstCoordinate;
    }

    public Coordinate[] getCoordinates() {
        return coordinates;
    }

    public Coordinate getLastCoordinate() {
        int last = decks - 1;
        return coordinates[last];
    }

    @Override
    public String toString() {
        return "firstCoordinate:" + firstCoordinate
                + " direction:" + direction.toString().toLowerCase()
                + " decks:" + decks;
    }

    private void locateCoordinates() {
        int h = firstCoordinate.getHorizontal();
        int v = firstCoordinate.getVertical();
        coordinates = new Coordinate[decks];
        coordinates[0] = firstCoordinate;

        if (direction == Direction.HORIZONTAL) {
            for (int i = 1; i < decks; i++)
                coordinates[i] = new Coordinate(v, h + i);
        } else {
            for (int i = 1; i < decks; i++)
                coordinates[i] = new Coordinate(v + i, h);
        }
    }
}
